//
//  LJHNewRunViewController.m
//  Sports-Go
//
//  Created by rimi on 16/9/29.
//  Copyright © 2016年 YRL. All rights reserved.
//

#import "LJHNewRunViewController1.h"

#import "LJHMapViewController.h"
#import <MapKit/MKMapView.h>
#import <AMapLocationKit/AMapLocationManager.h>
#import <CoreMotion/CMMotionManager.h>
#import "LJHMathCotroller.h"
#import "Run.h"
#import <AudioToolbox/AudioServices.h>
#import "RecordManager.h"
#import "LocationDataManager.h"
#import "CalendarViewController.h"
//#import <AVFoundation/AVSpeechSynthesis.h>

//static NSString * const detailSegueName = @"RunDetails";

@interface LJHNewRunViewController1 ()<AMapLocationManagerDelegate,MKMapViewDelegate>{
// 开始倒计时
    int     _downCount;
// 运动时间
    int     _seconds;
// 运动距离
    float   _distance;
// 是否准备
    BOOL    _isReady;
// 暂停计数
    int     _stopCount;
}
@property (nonatomic, strong, readwrite) UILabel *promptLabel;
@property (nonatomic, strong, readwrite) UILabel* timeLabel;
@property (nonatomic, strong, readwrite) UILabel* distLabel;
@property (nonatomic, strong, readwrite) UILabel* paceLabel;
@property (strong, nonatomic, readwrite) UILabel *kmLabel;
@property (strong, nonatomic, readwrite) UIImageView *timeImg;
@property (strong, nonatomic, readwrite) UIImageView *speedImg;
@property (nonatomic, strong)UIButton *pauseButton;//停止按钮
@property (nonatomic, strong)UIButton *startButton;//开始按钮
@property (nonatomic, strong)UIButton *stopButton;//结束按钮
@property (nonatomic, strong)UIButton *showMapButton;//地图按钮

// 定位管理
@property (nonatomic, strong) AMapLocationManager* locationManager;
// 运动位置数组
@property (nonatomic, strong) NSMutableArray* locations;
// 运动计时器
@property (nonatomic, strong) NSTimer *timer;
// 倒计时
@property(nonatomic,strong)NSTimer* downTimer;
// 运动管理
@property(nonatomic,strong)CMMotionManager* motionManger;

@property (nonatomic, strong)LJHMapViewController *mapViewController;
@property (nonatomic, strong, readwrite) Run *run;


@end

@implementation LJHNewRunViewController1

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.mapViewController.view];
    _downCount = 3;
    _stopCount = 0;
    _seconds = 0.00;
    _distance = 0.00;
    [self.locationManager startUpdatingLocation];
    //开启倒计时
    self.downTimer = [NSTimer
                      scheduledTimerWithTimeInterval:1.0f
                      target:self selector:@selector(countDown:)
                      userInfo:nil
                      repeats:YES];
    
    [self initLayout];
    
}
- (void)initLayout{
    [self.view addSubview:self.showMapButton];
    [self.view addSubview:self.promptLabel];
    [self.view addSubview:self.distLabel];
    [self.view addSubview:self.kmLabel];
    [self.view addSubview:self.timeLabel];
    [self.view addSubview:self.paceLabel];
    [self.view addSubview:self.speedImg];
    [self.view addSubview:self.timeImg];
    [self.view addSubview:self.pauseButton];
    [self.view addSubview:self.startButton];
    [self.view addSubview:self.stopButton];
    [self.view addSubview:self.mapViewController.view];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.mapViewController.view.hidden = YES;
    self.isReady = NO;
    [self mapButtonAnimation];
    
    [self.navigationController setNavigationBarHidden:YES];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    self.tabBarController.tabBar.hidden = NO;
    
    
    [self.timer invalidate];
    
    [self.locationManager stopUpdatingLocation];
    
    self.locationManager = nil;

}

#pragma mark - event response
/**
 *  倒计时回调
 */
- (void)countDown:(NSTimer*)timer {
    _downCount--;
    
    self.promptLabel.text = [NSString stringWithFormat:@"%d",_downCount];
    
    if (_downCount==0) {
        [self.downTimer invalidate];
        
        self.isReady  = YES;
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                      target:self
                                                    selector:@selector(eachSecond:)
                                                    userInfo:nil
                                                     repeats:YES];
    }
    
}



/**
 *  运动计数器回调
 */
- (void)eachSecond:(NSTimer*)timer {
    _seconds++;
    
    //刷新UI
    self.timeLabel.text = [NSString stringWithFormat:@"%@",[LJHMathCotroller stringifySecondCount:_seconds usingLongFormat:NO]];
    
    self.distLabel.text = [NSString stringWithFormat:@"%.2f",_distance/1000];
    
    self.paceLabel.text = [NSString stringWithFormat:@"%@",[LJHMathCotroller stringifyAvgPaceFromDist:_distance overTime:_seconds]];
}
//结束按钮
- (void)stopPressed:(UIButton *)sender{
//        AVSpeechSynthesizer *av = [[AVSpeechSynthesizer alloc]init];
//    
//    
//        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:@"3，2，1，开始"];
//    
//    AVSpeechSynthesisVoice *voiceType = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
//    utterance.voice = voiceType;
//    utterance.rate *= 0.7;
//        [av speakUtterance:utterance];
    if (_distance/1000>0.01) {
        [self saveRun];
    
    }else{
        
    }
     [self.navigationController popViewControllerAnimated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    [[segue destinationViewController] setRun:self.run];
}

//显示地图
- (void)pushToMap:(UIBarButtonItem *)sender{   

    self.mapViewController.view.transform= CGAffineTransformMakeScale(0.01, 0.01);
    
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        self.mapViewController.view.transform = CGAffineTransformIdentity;
        
        self.mapViewController.view.hidden = NO;
        
    } completion:^(BOOL finished) {
        
    }];
}

//暂停
- (void)pauseBtnClick:(UIButton *)sender{
    sender.hidden = YES;
    
    self.view.backgroundColor = [UIColor grayColor];
    
    self.startButton.hidden = NO;
    
    self.stopButton.hidden = NO;
    
    [self.timer invalidate];
    
    [self.locationManager stopUpdatingLocation];
    
    self.mapViewController.locateEnable = NO;
    
    [self.showMapButton.layer removeAllAnimations];
    
    //系统震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
    AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
//恢复
- (void)startClick:(UIButton *)sender{
    sender.hidden = YES;
    
    _stopCount = 0;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.stopButton.hidden = YES;
    
    self.pauseButton.hidden = NO;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                  target:self
                                                selector:@selector(eachSecond:)
                                                userInfo:nil
                                                 repeats:YES];
    
    [self.locationManager startUpdatingLocation];
    
    self.mapViewController.locateEnable = YES;
    
    [self mapButtonAnimation];
}
#pragma mark - private
/**
 *  保存跑步记录
 */
-(void)saveRun{
    NSMutableArray *locationArray = [NSMutableArray array];
    
    RecordManager* manager = [[RecordManager alloc]init];
    
    LocationDataManager* locationManager = [[LocationDataManager alloc]init];
    
    for (CLLocation *location in self.locations) {
        Location* locationObject =  [locationManager
                                     addLoactionWithLatitude:[NSNumber
                                                              numberWithDouble:location.coordinate.latitude] longtitude:[NSNumber numberWithDouble:location.coordinate.longitude] timestamp:location.timestamp];
        
        [locationArray addObject:locationObject];
        
    }
    
    Run* runObject =  [manager addRunRecordWithDis:[NSNumber
                                                    numberWithFloat:_distance]
                                           withDur:[NSNumber
                                                    numberWithInt:_seconds]
                                          withTime:[NSDate date]
                                     withLocations:[NSOrderedSet
                                                    orderedSetWithArray:locationArray]];
    
    self.run = runObject;
}

/**
 *  地图旋转动画
 */
-(void)mapButtonAnimation{
    CABasicAnimation* rotationAnimation;
    
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    
    rotationAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    
    rotationAnimation.toValue = [ NSValue valueWithCATransform3D:
                                 
                                 CATransform3DMakeRotation(M_PI, 0.0, 0.0, 1.0) ];
    
    rotationAnimation.duration = 1.0;
    
    rotationAnimation.cumulative = YES;
    
    rotationAnimation.repeatCount = MAXFLOAT;
    
    [self.showMapButton.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
}
#pragma mark - AMapLocationManagerDelegate
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    [_locationManager stopUpdatingLocation];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
    if (location.horizontalAccuracy < 30) {
        NSDate *eventDate = location.timestamp;
        
        NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
        
        if (fabs(howRecent) < 2.0 && location.horizontalAccuracy < 30) {
            if (self.locations.count > 0) {
                _distance += [location distanceFromLocation:self.locations.lastObject];
            }
            
            [self.locations addObject:location];
        }
    }
}
#pragma mark--Setter/Getter
-(AMapLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        
        _locationManager.delegate = self;
        
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        
        //设置允许后台定位参数，保持不会被系统挂起
        [_locationManager setPausesLocationUpdatesAutomatically:NO];
        
        if([[[UIDevice currentDevice] systemVersion] floatValue]>9.0){
            [_locationManager setAllowsBackgroundLocationUpdates:YES];//iOS9(含)以上系统需设置
        }
        
    }
    return _locationManager;
}
-(LJHMapViewController *)mapViewController{
    if (!_mapViewController) {
        _mapViewController =  [[LJHMapViewController alloc]init];
        _mapViewController.view.frame = RzCGRectMake(0, 0, 375, 667);
    }
    return _mapViewController;
}
- (UIButton *)showMapButton{
    if (!_showMapButton) {
        _showMapButton = [[UIButton alloc] initWithFrame:RzCGRectMake(15, 30, 40, 40)];
        [_showMapButton setImage:[UIImage imageNamed:@"Map"]  forState:UIControlStateNormal];
        [_showMapButton addTarget:self action:@selector(pushToMap:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _showMapButton;
}
- (UILabel *)promptLabel{
    if (!_promptLabel) {
        _promptLabel = [[UILabel alloc] initWithFrame:RzCGRectMake(0, 150, 375, 300)];
        
        _promptLabel.textAlignment = NSTextAlignmentCenter;
//        _promptLabel.font = [UIFont fontWithName:@"Knockout-HTF30-JuniorWelterwt" size:250];
        _promptLabel.font = [UIFont boldSystemFontOfSize:250];
        _promptLabel.textColor = getColor(25, 206, 248, 1);
        _promptLabel.text = @"3";
    }
    return _promptLabel;
}
- (UILabel *)distLabel{
    if (!_distLabel) {
        _distLabel = [[UILabel alloc] initWithFrame:RzCGRectMake(0, 100, 375, 120)];
        _distLabel.textAlignment = NSTextAlignmentCenter;
//        _distLabel.font = [UIFont fontWithName:@"Knockout-HTF30-JuniorWelterwt" size:120];
        
        _distLabel.font = [UIFont boldSystemFontOfSize:80];
        _distLabel.textColor = getColor(58, 206, 248, 1);
        _distLabel.text = @"0.00";
    }
    return _distLabel;
}
- (UILabel *)kmLabel{
    if (!_kmLabel) {
        _kmLabel = [[UILabel alloc] initWithFrame:RzCGRectMake(375-60, 120+120-20, 40, 20)];
        _kmLabel.textAlignment = NSTextAlignmentRight;
        _kmLabel.text = @"km";
        _kmLabel.textColor = getColor(58, 206, 248, 1);
        
        
    }
    return _kmLabel;
}
- (UILabel *)timeLabel{
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] initWithFrame:RzCGRectMake(375/4-50, 380, 100, 40)];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        _timeLabel.font = [UIFont fontWithName:@"Knockout-HTF30-JuniorWelterwt" size:19];
        _timeLabel.text = @"00:00";
        
    }
    return _timeLabel;
}
- (UILabel *)paceLabel{
    if (!_paceLabel) {
        _paceLabel = [[UILabel alloc] initWithFrame:RzCGRectMake(375/4*3-50, 380, 100, 40)];
        _paceLabel.textAlignment = NSTextAlignmentCenter;
        _paceLabel.font = [UIFont fontWithName:@"Knockout-HTF30-JuniorWelterwt" size:19];
        _paceLabel.text = @"0‘0’‘/km";
    }
    return _paceLabel;
}
- (UIImageView *)timeImg{
    if (!_timeImg) {
        _timeImg = [[UIImageView alloc] initWithFrame:RzCGRectMake(375/4-20, 310, 40, 40)];
        _timeImg.image = [UIImage imageNamed:@"time"];
        
    }
    return _timeImg;
}
- (UIImageView *)speedImg{
    if (!_speedImg) {
        _speedImg = [[UIImageView alloc] initWithFrame:RzCGRectMake(375/4*3-20, 310, 40, 40)];
        _speedImg.image = [UIImage imageNamed:@"speed"];
    }
    return _speedImg;
}
- (UIButton *)pauseButton{
    if (!_pauseButton) {
        _pauseButton = [[UIButton alloc] initWithFrame:RzCGRectMake(375/2-55, 500, 110, 110)];
        _pauseButton.backgroundColor = getColor(58, 206, 248, 1);
        [_pauseButton setImage:[UIImage imageNamed:@"pause"]  forState:UIControlStateNormal];
        [_pauseButton addTarget:self action:@selector(pauseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _pauseButton.layer.cornerRadius = 55*bi;
        _pauseButton.layer.masksToBounds = YES;
    }
    return _pauseButton;
}
- (UIButton *)startButton{
    if (!_startButton) {
        _startButton = [[UIButton alloc] initWithFrame:RzCGRectMake(375/4-55, 500, 110, 110)];
        _startButton.backgroundColor = getColor(58, 196, 248, 1);
        [_startButton setImage:[UIImage imageNamed:@"start"]  forState:UIControlStateNormal];
        [_startButton addTarget:self action:@selector(startClick:) forControlEvents:UIControlEventTouchUpInside];
        _startButton.layer.cornerRadius = 55*bi;
        _startButton.layer.masksToBounds = YES;
    }
    return _startButton;
}

- (UIButton *)stopButton{
    if (!_stopButton) {
        _stopButton = [[UIButton alloc] initWithFrame:RzCGRectMake(375/4*3-55, 500, 110, 110)];
        _stopButton.backgroundColor = getColor(234, 74, 75, 1);
        [_stopButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        [_stopButton addTarget:self action:@selector(stopPressed:) forControlEvents:UIControlEventTouchUpInside];
        _stopButton.layer.cornerRadius = 55*bi;
        _stopButton.layer.masksToBounds = YES;
    }
    return _stopButton;
}
-(NSMutableArray *)locations{
    if (!_locations) {
        _locations = [NSMutableArray arrayWithCapacity:10];
    }
    return _locations;
}

-(CMMotionManager *)motionManger{
    if (!_motionManger) {
        _motionManger = [[CMMotionManager alloc]init];
        _motionManger.gyroUpdateInterval = 1.0;
    }
    return _motionManger;
}

-(void)setIsReady:(BOOL)isReady{
    if (isReady) {
        self.promptLabel.hidden = YES;
        
        self.timeLabel.hidden = NO;
        
        self.distLabel.hidden = NO;
        
        self.paceLabel.hidden = NO;
        
        self.kmLabel.hidden = NO;
        
        self.pauseButton.hidden = NO;
        
        self.showMapButton.hidden  = NO;
        
        self.speedImg.hidden = NO;
        
        self.timeImg.hidden = NO;
        
        /**
         *  重力感应是否可用
         */
        NSOperationQueue* queue = [[NSOperationQueue alloc]init];
        if (self.motionManger.gyroAvailable) {
            
            [self.motionManger startGyroUpdatesToQueue:queue withHandler:^(CMGyroData * _Nullable gyroData, NSError * _Nullable error) {
                
                CGFloat y = gyroData.rotationRate.y;
                
                CGFloat z = gyroData.rotationRate.z;
                
                if (fabs(y)>2||fabs(z)>2) {
                    
                    _stopCount = 0;
                    
                    if (!self.startButton.hidden) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            if ([self respondsToSelector:@selector(startClick:)]) {
                                
                                [self startClick:self.startButton];
                                
                            }
                        });
                    }
                }else{
                    
                    _stopCount++;
                    
                    if (_stopCount>8&&self.startButton.hidden) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            if ([self respondsToSelector:@selector(pauseBtnClick:)]) {
                                
                                [self pauseBtnClick:self.pauseButton];
                            }
                        });
                        
                    }
                }
            }];
        }else{
          //  NSLog(@"重力感应不可用");
        }
    }else{
        self.promptLabel.hidden = NO;
        
        self.timeLabel.hidden = YES;
        
        self.distLabel.hidden = YES;
        
        self.paceLabel.hidden = YES;
        
        self.stopButton.hidden = YES;
        
        self.kmLabel.hidden = YES;
        
        self.pauseButton.hidden = YES;
        
        self.startButton.hidden = YES;
        
        self.showMapButton.hidden = YES;
        
        self.timeImg.hidden = YES;
        
        self.speedImg.hidden = YES;
        
    }
}


@end
